<script setup>
import * as echarts from 'echarts';
import router from "../../../router/index.js";
import {selectNode} from "../../../http/rabbitmq/node.js";
import {onMounted, onUnmounted, ref} from "vue";
import {onBeforeRouteLeave, useRoute} from "vue-router";
import moment from "moment";
import {rabbitmqStore} from "../../../stores/counter.js";
import byteTools from "../../../tools/ByteTools.js";
import ByteTools from "../../../tools/ByteTools.js";

const route = useRoute()

const nodeDetails = ref({})

let nodeMemStatsDetailsChartInstance = null
const nodeMemStatsDetails = ref([])

let nodeDiskStatsDetailsChartInstance = null
const nodeDiskStatsDetails = ref([])

const msgRates = ref("60_5")

function handleNodeSelect() {
  selectNode(route.query.name, msgRates.value).then(response => {
    nodeDetails.value = response
    nodeMemStatsDetails.value = response.mem_used_details.samples.reverse()
    nodeDiskStatsDetails.value = response.disk_free_details.samples.reverse()
    initNodeMemStats(nodeMemStatsDetails.value)
    initNodeDiskStats(nodeDiskStatsDetails.value)
  })
}

function initNodeMemStats(data) {
  if (nodeMemStatsDetailsChartInstance == null) {
    nodeMemStatsDetailsChartInstance = echarts.init(document.getElementById('node_mem_stats'))
    window.addEventListener("resize", function () {
      nodeMemStatsDetailsChartInstance.resize()
    })
  }
  const config = {
    color: ["#409EFF", "#F56C6C"],
    legend: {},
    grid: {
      left: '5%'
    },
    tooltip: {},
    dataset: {
      // 用 dimensions 指定了维度的顺序。直角坐标系中，如果 X 轴 type 为 category，
      // 默认把第一个维度映射到 X 轴上，后面维度映射到 Y 轴上。
      // 如果不指定 dimensions，也可以通过指定 series.encode
      // 完成映射，参见后文。
      dimensions: ['timestamp', 'sample', 'limit'],
      source: data
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: function (value, index) {
          return moment(parseInt(value)).format("yyyy-MM-DD HH:mm:ss").replace(' ', '\n')
        }
      }
    },
    yAxis: {
      position: "right",
      axisLabel: {
        formatter: function (value, index) {
          return byteTools.formatBytes(parseInt(value), 0)
        }
      }
    },
    series: [
      {
        type: 'line',
        name: 'mem used',
        tooltip: {
          formatter: function (params, ticket, callback) {
            let content = 'time: ' + moment(parseInt(params.data.timestamp)).format("yyyy-MM-DD HH:mm:ss") + '<br />'
            content = content + ' mem used: ' + byteTools.formatBytes(parseInt(params.data.sample))
            return content
          }
        },
      },
      {
        type: 'line',
        name: 'mem limit',
        tooltip: {
          formatter: function (params, ticket, callback) {
            debugger
            return "limit";
          }
        },
        markLine: {
          lineStyle: {
            color: "#F56C6C",
          },
          label: {
            color: "#F56C6C",

            normal: {
              formatter: function (data, index) {
                return byteTools.formatBytes(parseInt(data.value), 0)
              }
            }
          },
          data: [
            {
              yAxis: 500000000
            }
          ]
        }
      }
    ]
  };
  nodeMemStatsDetailsChartInstance.setOption(config)
}

function initNodeDiskStats(data) {
  if (nodeDiskStatsDetailsChartInstance == null) {
    nodeDiskStatsDetailsChartInstance = echarts.init(document.getElementById('node_disk_stats'))
    window.addEventListener("resize", function () {
      nodeDiskStatsDetailsChartInstance.resize()
    })
  }
  const config = {
    color: ["#409EFF", "#F56C6C"],
    legend: {},
    grid: {
      left: '5%'
    },
    tooltip: {},
    dataset: {
      dimensions: ['timestamp', 'sample', 'limit'],
      source: data
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: function (value, index) {
          return moment(parseInt(value)).format("yyyy-MM-DD HH:mm:ss").replace(' ', '\n')
        }
      }
    },
    yAxis: {
      position: "right",
      axisLabel: {
        formatter: function (value, index) {
          return byteTools.formatBytes(parseInt(value), 0)
        }
      }
    },
    series: [
      {
        type: 'line',
        name: 'disk free',
        tooltip: {
          formatter: function (params, ticket, callback) {
            let content = 'time: ' + moment(parseInt(params.data.timestamp)).format("yyyy-MM-DD HH:mm:ss") + '<br />'
            content = content + ' disk free: ' + byteTools.formatBytes(parseInt(params.data.sample))
            return content
          }
        },
      },
      {
        type: 'line',
        name: 'disk limit',
        tooltip: {
          formatter: function (params, ticket, callback) {
            debugger
            return "limit";
          }
        },
        markLine: {
          lineStyle: {
            color: "#F56C6C",
          },
          label: {
            color: "#F56C6C",
            normal: {
              formatter: function (data, index) {
                return byteTools.formatBytes(parseInt(data.value), 0)
              }
            }
          },
          data: [
            {
              yAxis: 5000000000
            }
          ]
        }
      }
    ]
  };
  nodeDiskStatsDetailsChartInstance.setOption(config)
}

const goBack = () => {
  router.push({path: '/node'})
}

onMounted(() => {
  handleNodeSelect()
  rabbitmqStore().setTimer(handleNodeSelect)
})

onUnmounted(() => {
  clearInterval(rabbitmqStore().timer)
  rabbitmqStore().deleteTimer()
})

onBeforeRouteLeave(() => {
  clearInterval(rabbitmqStore().timer)
  rabbitmqStore().deleteTimer()
})
</script>

<template>
  <el-page-header @back="goBack" style="height: 30px">
    <template #content>
      <span class="text-large font-600 mr-3"> {{ nodeDetails.name }} </span>
    </template>
    <template #extra>
      <el-form ref="form" :inline="true" :model="msgRates" label-width="80px">
        <el-form-item label="时间区间">
          <el-select v-model="msgRates" style="width: 220px" clearable
                     @change="handleNodeSelect()">
            <el-option
                v-for="item in rabbitmqStore().msgRates"
                :key="item.ukId"
                :label="item.name"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </template>
  </el-page-header>
  <div style="width: 100%; height: calc(100% - 60px); overflow: auto">
    <el-descriptions column="4" border>
      <el-descriptions-item label="Name">{{ nodeDetails.name }}</el-descriptions-item>
      <el-descriptions-item label="Type">{{ nodeDetails.type }}</el-descriptions-item>
      <el-descriptions-item label="Rates Mode">{{ nodeDetails.rates_mode }}</el-descriptions-item>
      <el-descriptions-item label="Uptime">{{ moment.duration(nodeDetails.uptime).humanize() }}</el-descriptions-item>
      <el-descriptions-item label="Config file" span="4">{{ nodeDetails.config_files }}</el-descriptions-item>
      <el-descriptions-item label="Database directory" span="4">{{ nodeDetails.db_dir }}</el-descriptions-item>
      <el-descriptions-item label="Log file" span="4">{{ nodeDetails.log_files }}</el-descriptions-item>
      <el-descriptions-item label="Plugins" span="4">{{ nodeDetails.enabled_plugins }}</el-descriptions-item>
      <el-descriptions-item label="Mem Strategy">{{ nodeDetails.mem_calculation_strategy }}</el-descriptions-item>
      <el-descriptions-item label="Run Queue">{{ nodeDetails.run_queue }}</el-descriptions-item>
      <el-descriptions-item label="Cores">{{ nodeDetails.processors }}</el-descriptions-item>
      <el-descriptions-item label="OS pid">{{ nodeDetails.os_pid }}</el-descriptions-item>
    </el-descriptions>
    <el-row :gutter="10" style="width: 100%">
      <el-col :span="12">
        <el-card>
          <div id="node_mem_stats" style="height: 300px">
            暂无数据
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div id="node_disk_stats" style="height: 300px">

          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-table highlight-current-row :data="nodeDetails.contexts" border>
      <el-table-column prop="description" label="description" min-width="100"/>
      <el-table-column prop="path" label="path" min-width="100"/>
      <el-table-column prop="port" label="port" width="100"/>
    </el-table>
    <el-table highlight-current-row :data="nodeDetails.cluster_links" border>
      <el-table-column prop="name" label="name" min-width="100"/>
      <el-table-column prop="peer_addr" label="peer_addr" min-width="100"/>
      <el-table-column prop="peer_port" label="peer_port" width="100"/>
      <el-table-column prop="recv_bytes" label="recv_bytes" width="100">
        <template #default="scope">
          {{ ByteTools.formatBytes(scope.row.recv_bytes, 0) }}
        </template>
      </el-table-column>
      <el-table-column prop="send_bytes" label="send_bytes" width="100">
        <template #default="scope">
          {{ ByteTools.formatBytes(scope.row.send_bytes, 0) }}
        </template>
      </el-table-column>
      <el-table-column prop="sock_addr" label="sock_addr" width="100"/>
      <el-table-column prop="sock_port" label="sock_port" width="100"/>
    </el-table>
  </div>

</template>

<style scoped>

</style>